<?php


class BaseModel {
    
    protected $_yiiDB;


    public function __construct() {
        $this->_yiiDB = Yii::app()->db;
        $this->cache = new RediskaBaseModel();
    }
    
    /*INSERT/UPDATE
     * $this->_yiiDB->createCommand($qs)->execute();
     */
    
    protected function _getCacheName($qs) {
        return "qs_".md5($qs);
    }

    public function getArray($qs, $cacheTime = null) {
        return $this->_getArray('queryAll', $qs, $cacheTime);
    }
    
    public function getCount($qs, $cacheTime = null) {
        return $this->_getArray('queryScalar', $qs, $cacheTime);
    }
    
    public function getOneArray($qs, $cacheTime = null) {
        return $this->_getArray('queryRow', $qs, $cacheTime);
    }
    
    private function _getArray($type, $qs, $cacheTime = null) {
        if($cacheTime) {
            $key = $this->_getCacheName($qs.$type);
            if($this->cache->exists($key)) {
                return $this->cache->get($key);
            } else {
                $result = $this->_yiiDB->createCommand($qs)->$type();
                $this->cache->set($key, $result, $cacheTime);
                return $result;
            }
        } else {
            return $this->_yiiDB->createCommand($qs)->$type();
        }
    }
}

